package com.aliyuncs.aui.service.impl;

import com.aliyuncs.aui.common.utils.MySQLUtil;
import com.aliyuncs.aui.dto.res.ReservationResponse;
import com.aliyuncs.aui.service.ResvService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Service
public class ResvServiceImpl implements ResvService {

    private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");

    private Date parseTimeString(String timeStr) {
        try {
            if (timeStr == null) {
                return null;
            }
            if ("24:00:00".equals(timeStr)) {
                timeStr = "23:59:59";
            }
            return TIME_FORMAT.parse(timeStr);
        } catch (ParseException e) {
            log.warn("时间格式解析失败: {}", timeStr, e);
            return null;
        }
    }

    private final MySQLUtil mySQLUtil;

    public ResvServiceImpl(MySQLUtil mySQLUtil) {
        this.mySQLUtil = mySQLUtil;
    }

    @Override
    public ReservationResponse updateReservationState(String resvId, String state) {
        if (!"已预定".equals(state) && !"已爽约".equals(state) && 
            !"进行中".equals(state) && !"已结束".equals(state)) {
            return ReservationResponse.builder()
                .code(400)
                .message("状态值只能是'已预定'、'已爽约'、'进行中'或'已结束'")
                .build();
        }

        String sql = "UPDATE resv SET state = ? WHERE resv_id = ?";
        try {
            int rows = mySQLUtil.executeUpdate(sql, state, resvId);
            if (rows > 0) {
            return ReservationResponse.builder()
                .code(200)
                .message("预定状态更新成功")
                .build();
        }
        return ReservationResponse.builder()
            .code(404)
            .message("未找到匹配的预定记录")
            .build();
        } catch (SQLException e) {
            e.printStackTrace();
            return ReservationResponse.builder()
                .code(500)
                .message("数据库操作失败：" + e.getMessage())
                .build();
        }
    }

    @Override
    public ReservationResponse createReservation(
            String tenantId,
            String resvTime,
            String tableNumber,
            String endTime,
            Integer duration,
            Integer pax) {
        if (tenantId == null || resvTime == null || tableNumber == null) {
            return ReservationResponse.builder()
                .code(400)
                .message("tenantId, resvTime和tableNumber不能为空")
                .build();
        }

        Date startTime = parseTimeString(resvTime);
        if (startTime == null) {
            return ReservationResponse.builder()
                .code(400)
                .message("开始时间格式错误，应为HH:mm")
                .build();
        }

        if (endTime == null && duration == null) {
            duration = 2;
        }

        Date endDate = null;
        if (endTime != null) {
            endDate = parseTimeString(endTime);
            if (endDate == null) {
            return ReservationResponse.builder()
                .code(400)
                .message("结束时间格式错误，应为HH:mm")
                .build();
            }
        }

        if (endDate == null) {
            endDate = new Date(startTime.getTime() + duration * 60 * 60 * 1000);
        } else if (duration == null) {
            duration = (int)((endDate.getTime() - startTime.getTime()) / (60 * 60 * 1000));
        }

        String sql = "INSERT INTO resv (tenant_id, resv_time, end_time, dur, table_number, pax, state, resv_id) " +
                   "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            String resvId = java.util.UUID.randomUUID().toString();
            int rows = mySQLUtil.executeUpdate(sql, 
                tenantId,
                TIME_FORMAT.format(startTime),
                TIME_FORMAT.format(endDate),
                duration,
                tableNumber,
                pax,
                "已预定",
                resvId
            );
            if (rows > 0) {
                return ReservationResponse.builder()
                    .code(200)
                    .message("预定创建成功")
                    .resvId(resvId)
                    .tenantId(tenantId)
                    .build();
            }
            return ReservationResponse.builder()
                .code(500)
                .message("预定创建失败")
                .build();
        } catch (SQLException e) {
            e.printStackTrace();
            return ReservationResponse.builder()
                .code(500)
                .message("数据库操作失败：" + e.getMessage())
                .build();
        }
    }
}
